package com.example.runningman;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.PermissionChecker;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.runningman.user.LoginActivity;
import com.example.runningman.util.DialogUtil;
import com.example.runningman.util.SPUtil;
import com.example.runningman.util.ScreenUtil;

import java.lang.ref.WeakReference;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

public class WelcomeActivity extends AppCompatActivity {
    ImageView bgIv;
    ImageView logoIv;
    TextView textView;
    MyHandler mhandler;
    boolean login=false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ScreenUtil.setFullScreen(this);
        ScreenUtil.keepScreenLight(this);
        ScreenUtil.hideNavigation(this);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);
        if(SPUtil.getInstance(WelcomeActivity.this).getString("phone",null)!=null){
            login=true;
        }

        initWelcomeAnim();
    }
    private void initWelcomeAnim() {
        bgIv = (ImageView) findViewById(R.id.bg_iv);
        logoIv = (ImageView) findViewById(R.id.logo_iv);
        textView= findViewById(R.id.text_iv);
        mhandler=new MyHandler(this);
        logoIv.setVisibility(View.INVISIBLE);
        textView.setVisibility(View.INVISIBLE);
        final AlphaAnimation alphaAnimation = new AlphaAnimation(0f, 1f);
        alphaAnimation.setDuration(1500);
        ScaleAnimation scaleAnimation = new ScaleAnimation(1f, 1.4f, 1f, 1.4f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        scaleAnimation.setDuration(2500);
        scaleAnimation.setFillAfter(true);

        scaleAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                mhandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        logoIv.setVisibility(View.VISIBLE);
                        logoIv.startAnimation(alphaAnimation);
                        textView.setVisibility(View.VISIBLE);
                        textView.startAnimation(alphaAnimation);
                    }
                }, 1000);
            }

            @Override
            public void onAnimationEnd(Animation animation) {
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
        bgIv.startAnimation(scaleAnimation);//开启动画
        if (Build.VERSION.SDK_INT >= 23) {
            CheckPermissions();

        } else {
            //小于6.0直接登陆进去

            timerTest();
        }
    }
    private class MyHandler extends Handler {
        private WeakReference<WelcomeActivity> mWeakReference;

        public MyHandler(WelcomeActivity activity) {
            mWeakReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            WelcomeActivity mainActivity = mWeakReference.get();
            super.handleMessage(msg);
            switch (msg.what) {
                case 111:
                    Intent intent;
                    if(login==true){
                        finish();

                        intent=new Intent(WelcomeActivity.this, MainActivity.class);
                        startActivity(intent);
                    }else {
                        finish();

                        intent=new Intent(WelcomeActivity.this, LoginActivity.class);
                        startActivity(intent);
                    }

                    break;

            }
        }
    };
    Timer timer;
    public  void timerTest(){
        //创建一个定时器
        timer = new Timer();
        //schedule方法是执行时间定时任务的方法
        timer.schedule(new TimerTask() {

            //run方法就是具体需要定时执行的任务
            @Override
            public void run() {
                mhandler.obtainMessage(111).sendToTarget();
            }
        }, 4000);

    }
    public void onDestroy() {
        timer.cancel();
        finish();
        super.onDestroy();
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == 5) {
            if (grantResults.length != 0) {
                int n = 0;
                for (int grantResult : grantResults) {
                    if (grantResult == PermissionChecker.PERMISSION_GRANTED) {
                        n++;//授权请求被允许
                    }
                }
                if (n != grantResults.length) {
                    CheckPermissions();
                    return;
                } else {
                    //权限允许完毕后调用
                    CheckPermissions();
                    Log.d("001", "onRequestPermissionsResult: ");
                }

            } else {
                CheckPermissions();
            }
        }
    }
    /**
     * 设置回调  从权限设置回来，所以回调
     */

    private boolean isFirst = true;
    /**
     * 权限检测
     */
    private void CheckPermissions() {
        //检测权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_WIFI_STATE) != PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_NETWORK_STATE) != PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            if (!isFirst) {
                //检测权限是否拒绝过
                if (!shouldShowRequestPermissionRationale(Manifest.permission.READ_EXTERNAL_STORAGE) ||
                        !shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_WIFI_STATE) ||
                        !shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_NETWORK_STATE) ||
                        !shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)) {
                    DialogUtil.showYN(this, "您已拒绝权限，请手动打开设置",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Toast.makeText(WelcomeActivity.this, "当前无权限，请授权！", Toast.LENGTH_SHORT).show();
                                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                    Uri uri = Uri.fromParts("package", WelcomeActivity.this.getPackageName(), null);
                                    intent.setData(uri);
                                    startActivityForResult(intent, 6);
                                    dialog=null;
                                }
                            },
                            new DialogInterface.OnClickListener() {

                                public void onClick(DialogInterface dialog, int which) {
                                    System.exit(0);
                                }
                            });
                    return;
                }
            }
            //请求权限
            ActivityCompat.requestPermissions(this, new String[]{
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.CAMERA,
                    Manifest.permission.CHANGE_WIFI_STATE,
                    Manifest.permission.ACCESS_WIFI_STATE,
                    Manifest.permission.CHANGE_WIFI_MULTICAST_STATE,
                    Manifest.permission.ACCESS_NETWORK_STATE,
                    Manifest.permission.CHANGE_NETWORK_STATE,
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.READ_PHONE_STATE
            }, 5);
            isFirst=false;
        } else {

            timerTest();
        }
    }
}
